package com.up4years.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.up4years.dataapi.dao.base.DBContextHolder;

/**
 * 事务开启之前 动态切换数据源
 * @author Administrator
 *
 */
@Aspect
@Component
public class DynamicDatasourceAspect implements Ordered{
	Logger logger = Logger.getLogger(DynamicDatasourceAspect.class); 
	
	
	@Around("execution(* query*(..))&&target(com.up4years.dataapi.service.base.CachedBaseManager) ")
	public Object whenQuery(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		DBContextHolder.setDBType(DBContextHolder.READ_DATA_SOURCE);
		return proceedingJoinPoint.proceed(); 		
	}
	@Around("execution(* get*(..))&&target(com.up4years.dataapi.service.base.CachedBaseManager) ")
	public Object whenGet(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		DBContextHolder.setDBType(DBContextHolder.READ_DATA_SOURCE);
		return proceedingJoinPoint.proceed(); 		
	}
	@Around("execution(* update*(..))&&target(com.up4years.dataapi.service.base.CachedBaseManager) ")
 	public Object whenUpdate(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
 		DBContextHolder.setDBType(DBContextHolder.WRITE_DATA_SOURCE);
 		return proceedingJoinPoint.proceed(); 		
  	}
	@Around("execution(* *nsert(..))&&target(com.up4years.dataapi.service.base.CachedBaseManager) ")
	public Object whenInsert(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		DBContextHolder.setDBType(DBContextHolder.WRITE_DATA_SOURCE);
		return proceedingJoinPoint.proceed(); 		
	}
	@Around("execution(* delete(..))&&target(com.up4years.dataapi.service.base.CachedBaseManager) ")
	public Object whenDel(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		DBContextHolder.setDBType(DBContextHolder.WRITE_DATA_SOURCE);
		return proceedingJoinPoint.proceed(); 		
	}
	@Around("within(com.up4years.cn..*) && within(!com.up4years.dataapi.service.base.CachedBaseManager)&& @annotation(org.springframework.transaction.annotation.Transactional) ")
	public Object whenService(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		DBContextHolder.setDBType(DBContextHolder.WRITE_DATA_SOURCE);
		return proceedingJoinPoint.proceed(); 		
	}

	@Override
	public int getOrder() {
		return 1;
	}
}
